package com.lngsyz.ywtb.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@MapperScan(basePackages = "com.lngsyz.ywtb.mapper.source1",sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSource1Config {
	@Value("${spring.datasource.druid.db1.url}")
    private String url;
    @Value("${spring.datasource.druid.db1.username}")
    private String username;
    @Value("${spring.datasource.druid.db1.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
	
    @Bean(name = "dataSource1")
    @ConfigurationProperties("spring.data-source1")
    public DruidDataSource oracleDataSource(){
    	DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(this.url);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        System.out.println("db1 init");
        return datasource;
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/source1/*.xml"));
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "source1TransactionManager")
    public DataSourceTransactionManager oracleTransactionManager(){
        return new DataSourceTransactionManager(oracleDataSource());
    }
}
